package com.demo.seata.tcc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.demo.seata.tcc.domain.TestLimit;
import com.demo.seata.tcc.service.TccLimitService;
import com.demo.seata.tcc.service.TestLimitService;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author
 * @since
 */
@Component
@Slf4j
public class TccLimitServiceImpl implements TccLimitService {

  @Autowired
  TestLimitService testLimitService;

  @Override
  @Transactional
  public boolean addLimitTry(TestLimit testLimit) {
    log.info("SEATA TCC trigger try :  TccLimitServiceImpl.addLimitTry ");
    return testLimitService.save(testLimit);
  }

  @Override
  public boolean addLimitConfirm(BusinessActionContext context) {
    log.info("SEATA TCC trigger confirm :TccLimitServiceImpl.addLimitConfirm: {}", context);
    return true;
  }

  @Override
  @Transactional
  public boolean addLimitCancel(BusinessActionContext context) {
    log.info("SEATA TCC trigger cancel :TccLimitServiceImpl.addLimitCancel:{}", context);
    TestLimit testLimit  =((JSONObject)context.getActionContext("testLimit")).toJavaObject(TestLimit.class);
    log.info("SEATA TCC trigger cancel : testLimit : {}", testLimit);
    Map delCondition = new HashMap<String, String>();
    delCondition.put("idno", testLimit.getIdno());
    testLimitService.removeByMap(delCondition);
    return true;
  }
}
